/*
 * Created by DuHuiling on 2017/2/24.
 */
var closeOpen = function(){
    var _open = document.getElementsByClassName('open')[0];
    if(_open){
        var _classArr = _open.className.split(" ");
        for(var i in _classArr){
            if(_classArr[i] == "open"){
                _classArr.splice(i,1);
            }
        }
        var _className = _classArr.join(" ");
        _open.className = _className;
    }
}
EventListener.addEventHandler(document,"onclick",function (e) {
    closeOpen();
});
/**
 * SelectDropDown组件
 * @class SelectDropDown
 * @extends Basic
 *
 * @param [value] 默认值
 * @param [className] 样式名
 * @param [options] 下拉选项数据　option选项　value选项对应的值
 * @param [onChange] 下拉选择后回调
 * @param [showTitle] 是否显示选项的title，option太长时建议显示
 * @param [disabled] 禁止点击下拉，默认false
 * @param [placeholder] 是否显示placeholder样式，默认true，下拉改变后为false
 * @param [defaultValue] 默认值，option对应的value,默认为：请选择
 * @param [fuzzy] true支持模糊搜索，false不支持模糊搜索
 * @param [inputChange] 搜索时输入框回调
 *
 * 示例:
 *
 *     @example
 *     <SelectDropDown options={[{option:'选项1',value:'1'},{option:'选项2',value:'2'}]}  />
 */
var SelectDropDown = React.createClass({
    getDefaultProps: function () {
        return {
            id:"",
            value: "",//默认初始值
            className: "",
            disabled:false,
            type: "", //三种类型，bank,search
            showNum: "", //显示下拉个数，超出显示滚动条(未实现)
            showTitle:true,  //显示title
            options: "",
            defaultValue: "请选择",
            defaultIndex:null,
            searchButton: "",
            placeholder: "",
            fuzzy: false,//true支持模糊搜索，false不支持模糊搜索
            inputChange: "",//搜索时输入框回调
            buttonClick: "",//搜索时按钮回调
            _dmid: new UDM({}).dmbind /*为每个 select-dropdown 创建udmid*/
        }
    },
    getInitialState:function(){
        return{
            options: this.props.options,
            currentIdx:this.props.defaultIndex,
            currentValue:null,
            currentText:'',
            _className:this.props.className ? "ucs-select-dropdown "+ this.props.className : "ucs-select-dropdown",
            searchInputVal: ""
        }
    },
    /**
     * @param v 修改下拉选项
     * */
    setOptions:function (v) {
        this.setState({
            options:v
        })
    },
    componentDidMount:function () {
        var defaultIndex = this.props.defaultIndex;
        var defaultValue = this.props.defaultValue;
        var indexOptin,valueOption;
        if(typeof defaultIndex =='number' && this.state.options[defaultIndex]){
            this.setState({
                currentIdx:defaultIndex,
                currentText: this.state.options[defaultIndex].option,
                currentValue: this.state.options[defaultIndex].value
            });

        }else if(defaultValue) {
            this.state.options.map(function (item,index) {
                if(item.value == defaultValue){
                    indexOptin = index;
                }
            });
            valueOption = (typeof indexOptin == "number") ? this.state.options[indexOptin].option : defaultValue;
            this.setState({
                currentIdx:indexOptin,
                currentValue:defaultValue,
                currentText: valueOption
            });
        }else {
            this.setState({
                currentText: '请选择'
            });
        }
    },
    _toggle:function(ref,e){
        if(this.props.disabled){
            return;
        }

        var _current = this.refs[this.props._dmid];
        var e = e || window.event;
        //console.log(e)
        if(e && e.stopPropagation){
            //因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        }else{
            //否则我们使用ie的方法来取消事件冒泡
            window.event.cancelBubble = true;
        }
        this.setState({
            _className:this._toggleOpen(_current.className)
        })
    },
    _toggleOpen: function(_class){
        closeOpen();
        var _classList = _class.split(" ");
        var j = 0;
        for(var i=0; i<_classList.length;i++){
            if(_classList[i] == "open"){
                j = i;
            }
        }
        if(j){
            _classList.splice(j,1);
        }else{
            _classList.push('open');
        }
        _classList = _classList.join(" ");
        return _classList;
    },
    _select:function(idx,val,ref){
        var _node = this.refs[ref],
            _input = this.refs[ref + '-control'];
        // _node.className = this._toggleOpen(_node.className);
        this.setState({
            _className:this._toggleOpen(_node.className)
        })
        _input.innerHTML = this.state.options[idx].option;

        this.state.currentIdx = idx;
        if(val.value){
            this.setState({
                currentText: val.option,
                currentValue: val.value
            });
        }else{
            this.setState({
                currentText: val.option,
                currentValue: idx
            });
        }

        var _v = this.getCurrentSelect();
        this.props.onChange ? this.props.onChange(_v) : "";
    },
    /**
     * 获取当前选择的值
     * @return {json}
     * */
    getCurrentSelect:function(){
        return {
            selectIndex:this.state.currentIdx,
            selectValue:this.state.currentValue,
            selectText:this.state.currentText
        }
    },
    searchClickHandler: function(e){
        var e = e || window.event;
        if(e && e.stopPropagation){
            //因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        }else{
            //否则我们使用ie的方法来取消事件冒泡
            window.event.cancelBubble = true;
        }
    },
    searchKeyupHandler: function(e){
        var _this = this;
        var e = e || window.event;
        even = e.srcElement?e.srcElement:e.target;
        var opts = _this.state.options;
        var len = opts.length;
        var arr = [];
        var iArr = [];
        var reg = new RegExp(even.value);
        for(var i=0;i<len;i++){
            //如果字符串中不包含目标字符会返回-1
            if(opts[i].option.match(reg)){
                arr.push(opts[i]);
                iArr.push(i);
            }
        }
        var element = this.refs[_this.props._dmid + '-dropdown-list'];
        while (element.firstChild) {
            element.removeChild(element.firstChild);
        }
        if(arr.length == 0){
            this.refs[this.props._dmid + '-dropdown-list'].appendChild(
                <li>无查询结果！</li>
            );
        }else{
            if(_this.props.showTitle){
                for(var i = 0; i < arr.length; i++){
                    this.refs[this.props._dmid + '-dropdown-list'].appendChild(
                        <li title={arr[i].option} onClick={_this._select.bind(_this,i,iArr[i],_this.props._dmid)}>
                            {arr[i].option}
                        </li>
                    );
                }
            }else{
                for(var i = 0; i < arr.length; i++){
                    this.refs[this.props._dmid + '-dropdown-list'].appendChild(
                        <li onClick={_this._select.bind(_this,i,iArr[i],_this.props._dmid)}>
                            {arr[i].option}
                        </li>
                    );
                }
            }

        }
    },
    /*下拉选项列表*/
    /*selectList: function(){
        var _lis = [],_that = this;
        for(var i=0; i<this.state.options.length;i++){
            (function(j,val,ref){
                if(_that.props.showTitle){
                    _lis.push(
                        <li title={_that.state.options[j].option} onClick={_that._select.bind(_that,j,val,ref)}>
                            {_that.state.options[j].option}
                        </li>
                    );
                }else{
                    _lis.push(
                        <li onClick={_that._select.bind(_that,j,val,ref)}>
                            {_that.state.options[j].option}
                        </li>
                    );
                }

            })(i,this.state.options[i],this.props._dmid);
        }
        return <ul>{_lis}</ul>
    },*/
    render:function(){
        /*判断defaultValue是否是数字，“是”则代表默认显示第几个选项*/
        var _this = this;
        var defaultValue = _this.state.currentText;
        var _class = _this.props.disabled?_this.state._className+" ucs-disabled":_this.state._className;
        return (
            <div className={_class} ref = {_this.props._dmid}>
                <div className="ucs-select-control" ref={_this.props._dmid + '-select-click'} onClick={_this._toggle.bind(_this,_this.props._dmid + '-select-click')}>
                    <div className="ucs-input" ref={_this.props._dmid + '-control'} title={_this.props.showTitle ? _this.state.currentText : ''}>{_this.state.currentText}</div>
                    <span className="ucs-icon"></span>
                </div>
                <div className="ucs-dropdown">
                    {
                        _this.props.fuzzy ? (
                            <div className="ucs-dropdown-border">
                                <div className="usc-dropdown-search"><input type="text" onClick={_this.searchClickHandler.bind(_this)} onKeyup={_this.searchKeyupHandler.bind(_this)}/></div>
                                <ul ref={_this.props._dmid + '-dropdown-list'}>
                                    {
                                        _this.state.options.map(function(opt,index){
                                           if(_this.props.showTitle){
                                               return (
                                                   <li title={opt.option} onClick={_this._select.bind(_this,index,opt,_this.props._dmid)}>
                                                       {opt.option}
                                                   </li>
                                               )
                                           }else{
                                               return (
                                                   <li onClick={_this._select.bind(_this,index,opt,_this.props._dmid)}>
                                                       {opt.option}
                                                   </li>
                                               )
                                           }
                                        })
                                    }
                                </ul>
                            </div>
                        ):(
                            <div className="ucs-dropdown-border">
                                <ul ref={_this.props._dmid + '-dropdown-list'}>
                                    {
                                        _this.state.options.map(function(opt,index){
                                            if(_this.props.showTitle){
                                                return (
                                                    <li title={opt.option} onClick={_this._select.bind(_this,index,opt,_this.props._dmid)}>
                                                        {opt.option}
                                                    </li>
                                                )
                                            }else{
                                                return (
                                                    <li onClick={_this._select.bind(_this,index,opt,_this.props._dmid)}>
                                                        {opt.option}
                                                    </li>
                                                )
                                            }
                                        })
                                    }
                                </ul>
                            </div>
                        )
                    }
                </div>
            </div>
        )
    }
});
module.exports = SelectDropDown;